const { adminInfo } = require('../config/config'),
  { addAdminData, loginCheckInfo } = require('../services/AdminService'),
  { makeCrypto, trimSpace, returnInfo } = require('../libs/utils'),
  errorInfo = require('../config/error_config'),
  { LOGIN } = errorInfo; //登录信息配置

const pageConf = require('../config/config').pageConf;

//service
const ProblemService = require('../services/Problem');
const ProblemTypeService = require('../services/ProblemType');
const DataTableService = require('../services/DataTable');

const middleWare = {
  async updateDataTablePid() {
    //增加题目pid集合的数据
    const problemsRes = await ProblemService.getAllProblems();
    let pidArr = [];
    problemsRes.forEach((item, index) => {
      pidArr.push(item.pid);
    })
    let pidStr = pidArr.join(',');
    //更新集合
    await DataTableService.addData({
      all_problem_pid: pidStr,
      all_problem_num: problemsRes.length
    })
  },
 
  async updateDataTableType() {
    //增加题目pid集合的数据
    const pType = await ProblemTypeService.getAllProblemType();
    let pBasicTypeArr = [],
        pAdvanceTypeArr = [];
    pType.forEach((item, index) => {
      if(item.isBasic == 1) {
        pBasicTypeArr.push(item.id);
      }else {
        pAdvanceTypeArr.push(item.id);
      }
    })

    let pBasicTypeStr = pBasicTypeArr.join(',');
    let pAdvanceTypeStr = pAdvanceTypeArr.join(',');
    
    //更新集合
    await DataTableService.addData({
      all_basic_type: pBasicTypeStr,
      all_advance_type: pAdvanceTypeStr
    })
  }
}


class AdminController {

  /* 添加题目页面*/
  async getAddProblemPage(ctx, next) {
    const problemTypes = await ProblemTypeService.getAllProblemType();

    await ctx.render('add_problem', {
      pageConf: pageConf.add_problem,
      problemTypes
    })
  }

  /* 添加题目*/
  async addProblem(ctx, next) {
    const problemData = ctx.request.body;
    //添加
    const res = await ProblemService.addProblem(problemData);

    //更新
    await middleWare.updateDataTablePid();

    if (res) {
      ctx.body = {
        code: 0,
        msg: 'add success'
      }
      ctx.response.redirect('/admin/manage-problem');
    } else {
      ctx.body = {
        code: 10003,
        msg: 'add failed'
      }
    }
  }

  /* 管理题目页面*/
  async getManageProblem(ctx, next) {
    const problems = await ProblemService.getAllProblems();
    const problemType = await ProblemTypeService.getAllProblemType();

    problems.map((item, index) => {
      for (var i = 0; i < problemType.length; i++) {
        if (item.problemTypeId === problemType[i].id) {
          item.type = problemType[i].type_title;
          break;
        }
      }
      return item;
    })

    await ctx.render('manage_problem', {
      pageConf: pageConf.manageProblem,
      problemList: problems
    })
  }

  /* 编辑题目页面*/
  async getEditProblem(ctx, next) {
    const pid = ctx.params.pid;
    const problemData = await ProblemService.findProblemById(pid);
    await ctx.render('edit_problem', {
      pageConf: pageConf.editProblem,
      problemData: problemData
    })
  }


  /* 编辑题目*/
  async editProblem(ctx, next) {
    const data = ctx.request.body;

    const res = await ProblemService.addProblem(data);
    if (res) {
      ctx.body = {
        cide: 0,
        msg: 'add success'
      }
      ctx.response.redirect('/admin/manage-problem')
    } else {
      ctx.body = {
        colde: 10001,
        msg: 'edit fail'
      }
    }
  }

  /* 删除题目*/
  async deleteProblem(ctx, next) {
    const pid = ctx.params.pid;

    const res = await ProblemService.deleteProblemById(pid);

    //更新
    await middleWare.updateDataTablePid();

    if (res) {
      ctx.response.redirect('/admin/manage-problem');
    } else {
      ctx.body = {
        code: 10002,
        msg: 'delete failed'
      }
    }
  }





  /********************************************************************/





  /* 添加题目类型页面*/
  async getAddProblemTypePage(ctx, next) {

    await ctx.render('add_problem_type', {
      pageConf: pageConf.add_problem_type
    })
  }

  /* 添加题目类型*/
  async addProblemType(ctx, next) {
    const problemData = ctx.request.body;
    const res = await ProblemTypeService.addProblemType(problemData);

    await middleWare.updateDataTableType();

    if (res) {
      ctx.body = {
        cide: 0,
        msg: 'add success'
      }
      ctx.response.redirect('/admin/manage-problem-type');
    } else {
      ctx.body = {
        code: 10003,
        msg: 'add failed'
      }
    }
  }

  /* 管理题目类型页面*/
  async getManageProblemType(ctx, next) {
    const problemTypes = await ProblemTypeService.getAllProblemType();

    await ctx.render('manage_problem_type', {
      pageConf: pageConf.manageProblemType,
      problemList: problemTypes
    })
  }

  /* 编辑题目类型页面*/
  async getEditProblemType(ctx, next) {
    const id = ctx.params.id;
    const problemTypeData = await ProblemTypeService.findProblemTypeById(id);

    await ctx.render('edit_problem_type', {
      pageConf: pageConf.editProblemType,
      problemTypeData: problemTypeData
    })
  }


  /* 编辑题目类型*/
  async editProblemType(ctx, next) {
    const data = ctx.request.body;

    const res = await ProblemTypeService.addProblemType(data);
    if (res) {
      ctx.body = {
        cide: 0,
        msg: 'add success'
      }
      ctx.response.redirect('/admin/manage-problem-type')
    } else {
      ctx.body = {
        colde: 10001,
        msg: 'edit fail'
      }
    }
  }

  /* 删除题目类型*/
  async deleteProblemType(ctx, next) {
    const id = ctx.params.id;

    const res = await ProblemTypeService.deleteProblemTypeById(id);

    await middleWare.updateDataTableType();

    if (res) {
      ctx.response.redirect('/admin/manage-problem-type');
    } else {
      ctx.body = {
        code: 10002,
        msg: 'delete failed'
      }
    }
  }







  /************************************************/

  /* 登录注册相关*/

  /* 创建用户*/
  async createAdmin(ctx, next) {
    //加密
    adminInfo.password = makeCrypto(adminInfo.password);

    const result = await addAdminData(adminInfo);
    if (result) {
      console.log(0);
    } else {
      console.log(1);
    }
  }

  //登录页
  async getLoginPage(ctx, next) {
    await ctx.render('admin/login', {

    })
  }


  //登录状态验证 判断登录状态  
  async loginCheck(ctx, next) {
    //检查两个条件是否满足，满足才算登录状态
    //用户登录时携带了cookie，服务器管理中间件会自动识别匹配
    //匹配成功的时候，会得到ctx.session.userInfo的信息
    if (ctx.session && ctx.session.userInfo) {
      //登录状态
      ctx.body = returnInfo(LOGIN.LOGIN_STATUS);
      return;
    }

    ctx.body = returnInfo(LOGIN.NOT_LOGIN_STATUS);
  }


  /* 登录*/
  async loginAction(ctx, next) {
    const { username, password } = ctx.request.body;

    if (!username || !password) {
      ctx.body = returnInfo(LOGIN.INVALID_OPERATION);
      return;
    }

    if (trimSpace(username).length <= 0) {
      ctx.body = returnInfo(LOGIN.INVALID_USERNAME_LENGTH);
      return;
    }

    if (trimSpace(password).length <= 0) {
      ctx.body = returnInfo(LOGIN.INVALID_PASSWORD_LENGTH);
      return;
    }

    //组合管理员用户信息
    const userInfo = {
      username: trimSpace(username),
      password: makeCrypto(trimSpace(password))
    }

    const result = await loginCheckInfo(userInfo);

    if (result === 10003) {
      ctx.body = returnInfo(LOGIN.USERNAME_NOT_EXIST);
      return;
    }

    if (result === 10004) {
      ctx.body = returnInfo(LOGIN.PASSWORD_ERROR);
      return;
    }


    //这里设置session的东西
    if (!ctx.session.userInfo) {
      //访问userInfo是否存在，不存在就是undefined，此时设置
      ctx.session.userInfo = result;
    }

    ctx.body = returnInfo(LOGIN.SUCCESS, ctx.session.userInfo); //成功返uid和username数据 传入
  }

  /* 退出登录*/
  async logoutAction(ctx, next) {
    delete ctx.session.userInfo;
    ctx.body = returnInfo(LOGIN.LOGOUT_SUCCESS);
  }

}

module.exports = new AdminController();